﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DigitalPlatform.Entities;
using DigitalPlatform.IDAL;
using Microsoft.EntityFrameworkCore;

namespace DigitalPlatform.DAL
{
    public class LocalDataAccess : ILocalDataAccess
    {
        private readonly ILocalEFService _localEFService;

        public LocalDataAccess(ILocalEFService localEFService)
        {
            this._localEFService = localEFService;
        }

        public async Task SaveEntities<T>(IList<T> devices) where T : class
        {
            try
            {
                await _localEFService.DBContext.Set<T>().AddRangeAsync(devices);
                await SaveChanges();
            }
            catch (Exception)
            {
                //此处可捕获出现的异常
            }
        }

        public async Task<IList<T>> QueryEntities<T>() where T : class
        {
            return await (_localEFService.DBContext as LocalEFService).Set<T>().ToListAsync();
        }


        public async Task RemoveAll<T>() where T : class
        {
            await Task.Run(async () =>
             {
                 (_localEFService.DBContext as LocalEFService).DeviceList.ExecuteDelete(); 
                 await SaveChanges();
             });
        }

        public async Task SaveChanges()
        {
            await _localEFService.DBContext.SaveChangesAsync();
        }
    }
}
